package com.bawei.module_goods.ui

import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import android.widget.Button
import android.widget.Toast
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bawei.module_goods.R
import com.bawei.module_goods.ui.adapter.HistoryAdapter
import kotlinx.coroutines.flow.collectLatest
import android.widget.EditText
class GoodsSearchActivity : AppCompatActivity() {
    private val viewModel by viewModels<GoodsSearchViewModel>()
    private lateinit var adapter: SearchGoodsAdapter
    private lateinit var suggestAdapter: SearchGoodsAdapter
    private lateinit var historyAdapter: HistoryAdapter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_goods_search)

        val etKeyword = findViewById<EditText>(R.id.et_keyword)
        val rvResult = findViewById<RecyclerView>(R.id.rv_search_result)
        val rvSuggest = findViewById<RecyclerView>(R.id.rv_suggest)
        val btnClearHistory = findViewById<View>(R.id.tv_clear_history)
        val layoutHistory = findViewById<View>(R.id.layout_history)
        val layoutSuggest = findViewById<View>(R.id.layout_suggest)
        val flexboxHistory = findViewById<com.google.android.flexbox.FlexboxLayout>(R.id.flexbox_history)

        adapter = SearchGoodsAdapter()
        rvResult.layoutManager = LinearLayoutManager(this)
        rvResult.adapter = adapter

        suggestAdapter = SearchGoodsAdapter()
        rvSuggest.layoutManager = LinearLayoutManager(this)
        rvSuggest.adapter = suggestAdapter

        // 移除historyAdapter和rvHistory相关
        // historyAdapter = HistoryAdapter { ... }
        // rvHistory.layoutManager = LinearLayoutManager(this)
        // rvHistory.adapter = historyAdapter

        // 监听软键盘搜索键
        etKeyword.setOnEditorActionListener { v, actionId, event ->
            if (actionId == android.view.inputmethod.EditorInfo.IME_ACTION_SEARCH) {
                val keyword = etKeyword.text?.toString()?.trim() ?: ""
                if (keyword.isNotEmpty()) {
                    // 只在这里保存历史
                    com.bawei.module_goods.util.SearchHistoryManager.saveHistory(this, keyword)
                    viewModel.processIntent(this, SearchIntent.LoadHistory)
                    viewModel.processIntent(this, SearchIntent.Search(keyword))
                } else {
                    Toast.makeText(this, "请输入关键字", Toast.LENGTH_SHORT).show()
                }
                true
            } else {
                false
            }
        }

        btnClearHistory.setOnClickListener {
            viewModel.processIntent(this, SearchIntent.ClearHistory)
        }

        etKeyword.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {}
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                val keyword = s?.toString() ?: ""
                if (keyword.isNotEmpty()) {
                    // 显示建议，隐藏历史
                    layoutSuggest.visibility = View.VISIBLE
                    layoutHistory.visibility = View.GONE
                    viewModel.processIntent(this@GoodsSearchActivity, SearchIntent.Suggest(keyword))
                } else {
                    // 显示历史，隐藏建议
                    layoutSuggest.visibility = View.GONE
                    layoutHistory.visibility = View.VISIBLE
                }
            }
        })

        suggestAdapter.setOnItemClickListener { item ->
            etKeyword.setText(item.name ?: "")
            etKeyword.setSelection(item.name?.length ?: 0)
            viewModel.processIntent(this, SearchIntent.Search(item.name ?: ""))
        }

        lifecycleScope.launchWhenStarted {
            viewModel.uiState.collectLatest { state ->
                if (state.error != null) {
                    Toast.makeText(this@GoodsSearchActivity, state.error, Toast.LENGTH_SHORT).show()
                }
                adapter.submitList(state.result)
                suggestAdapter.submitList(state.suggestions)
                // 用flexboxHistory显示历史标签
                flexboxHistory.removeAllViews()
                state.history.forEach { keyword ->
                    val tv = android.widget.TextView(this@GoodsSearchActivity).apply {
                        text = keyword
                        setPadding(32, 16, 32, 16)
                        setBackgroundResource(android.R.drawable.btn_default)
                        setTextColor(resources.getColor(android.R.color.black))
                        textSize = 14f
                        setOnClickListener {
                            etKeyword.setText(keyword)
                            etKeyword.setSelection(keyword.length)
                            viewModel.processIntent(this@GoodsSearchActivity, SearchIntent.Search(keyword))
                        }
                    }
                    val lp = com.google.android.flexbox.FlexboxLayout.LayoutParams(
                        com.google.android.flexbox.FlexboxLayout.LayoutParams.WRAP_CONTENT,
                        com.google.android.flexbox.FlexboxLayout.LayoutParams.WRAP_CONTENT
                    )
                    lp.setMargins(16, 8, 16, 8)
                    tv.layoutParams = lp
                    flexboxHistory.addView(tv)
                }
            }
        }

        viewModel.processIntent(this, SearchIntent.LoadHistory)
    }
} 